<template>
  <el-card class="statistics-report-container">
    <h2>统计分析与报表</h2>

    <!-- 使用率统计 -->
    <el-card class="section-card">
      <template #header>
        <span>使用率统计</span>
      </template>
      <div class="chart-container">
        <div class="chart-wrapper">
          <div class="chart-title">会议室使用率</div>
          <div ref="usageRateChart" class="chart"></div>
        </div>
        <div class="chart-wrapper">
          <div class="chart-title">高峰时段分布</div>
          <div ref="peakTimeChart" class="chart"></div>
        </div>
      </div>
    </el-card>

    <!-- 预约分析 -->
    <el-card class="section-card">
      <template #header>
        <span>预约分析</span>
      </template>
      <div class="chart-container">
        <div class="chart-wrapper">
          <div class="chart-title">热门会议室 TOP5</div>
          <div ref="popularRoomsChart" class="chart"></div>
        </div>
        <div class="chart-wrapper">
          <div class="chart-title">会议用途分布</div>
          <div ref="purposeChart" class="chart"></div>
        </div>
        <div class="chart-wrapper">
          <div class="chart-title">会议时长分布</div>
          <div ref="durationChart" class="chart"></div>
        </div>
      </div>
    </el-card>

    <!-- 违规统计 -->
    <el-card class="section-card">
      <template #header>
        <span>违规统计</span>
      </template>
      <div class="chart-container">
        <div class="chart-wrapper">
          <div class="chart-title">违规类型分布</div>
          <div ref="violationTypeChart" class="chart"></div>
        </div>
        <div class="chart-wrapper">
          <div class="chart-title">黑名单用户 TOP5</div>
          <div ref="blacklistChart" class="chart"></div>
        </div>
      </div>
    </el-card>

    <!-- 资源使用统计 -->
    <el-card class="section-card">
      <template #header>
        <span>资源使用统计</span>
      </template>
      <div class="chart-container">
        <div class="chart-wrapper">
          <div class="chart-title">设备使用频率</div>
          <div ref="deviceUsageChart" class="chart"></div>
        </div>
        <div class="chart-wrapper">
          <div class="chart-title">设备报修情况</div>
          <div ref="repairChart" class="chart"></div>
        </div>
      </div>
    </el-card>

    <!-- 自定义报表 -->
    <el-card class="section-card">
      <template #header>
        <span>自定义报表</span>
      </template>
      <div class="custom-report-filters">
        <el-form :model="filterForm" label-width="100px">
          <el-form-item label="时间范围">
            <el-date-picker
                v-model="filterForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item label="会议室">
            <el-select v-model="filterForm.room" multiple placeholder="请选择会议室">
              <el-option
                  v-for="room in availableRooms"
                  :key="room.id"
                  :label="room.name"
                  :value="room.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="统计类型">
            <el-select v-model="filterForm.reportType" placeholder="请选择统计类型">
              <el-option label="使用率分析" value="usage" />
              <el-option label="预约分析" value="booking" />
              <el-option label="违规分析" value="violation" />
              <el-option label="资源分析" value="resource" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="generateReport">生成报表</el-button>
            <el-button @click="exportReport('pdf')">导出PDF</el-button>
            <el-button @click="exportReport('excel')">导出Excel</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="chart-container">
        <div class="chart-wrapper">
          <div class="chart-title">数据图表</div>
          <div ref="customChart" class="chart"></div>
        </div>
      </div>
    </el-card>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import { ElMessage } from 'element-plus';

// 筛选表单数据
const filterForm = ref({
  dateRange: '',
  room: [],
  reportType: ''
});

// 会议室列表
const availableRooms = ref(
    Array.from({length: 30}, (_, i) => {
      const buildingIndex = i % 7;
      const building = String.fromCharCode(65 + buildingIndex); // A-G
      const floor = Math.floor(i / 7) + 1;
      const roomNum = 100 + (i % 20);
      return {
        id: `room${i+1}`,
        name: `${building}区${building}${floor}号楼${roomNum}`
      };
    })
);

// 图表引用
const usageRateChart = ref<HTMLElement | null>(null);
const peakTimeChart = ref<HTMLElement | null>(null);
const popularRoomsChart = ref<HTMLElement | null>(null);
const purposeChart = ref<HTMLElement | null>(null);
const durationChart = ref<HTMLElement | null>(null);
const violationTypeChart = ref<HTMLElement | null>(null);
const blacklistChart = ref<HTMLElement | null>(null);
const deviceUsageChart = ref<HTMLElement | null>(null);
const repairChart = ref<HTMLElement | null>(null);
const customChart = ref<HTMLElement | null>(null);

// 图表实例
let usageRateChartInstance: ECharts | null = null;
let peakTimeChartInstance: ECharts | null = null;
let popularRoomsChartInstance: ECharts | null = null;
let purposeChartInstance: ECharts | null = null;
let durationChartInstance: ECharts | null = null;
let violationTypeChartInstance: ECharts | null = null;
let blacklistChartInstance: ECharts | null = null;
let deviceUsageChartInstance: ECharts | null = null;
let repairChartInstance: ECharts | null = null;
let customChartInstance: ECharts | null = null;

// 初始化所有图表
const initCharts = () => {
  initUsageRateChart();
  initPeakTimeChart();
  initPopularRoomsChart();
  initPurposeChart();
  initDurationChart();
  initViolationTypeChart();
  initBlacklistChart();
  initDeviceUsageChart();
  initRepairChart();
};

// 使用率统计图表 - 使用动态会议室名称
const initUsageRateChart = () => {
  if (usageRateChart.value) {
    usageRateChartInstance = echarts.init(usageRateChart.value);

    // 使用动态会议室名称
    const roomNames = availableRooms.value.slice(0, 5).map(room => room.name);

    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>使用率: {c}%'
      },
      xAxis: {
        type: 'category',
        data: roomNames,
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      },
      series: [{
        name: '使用率',
        type: 'bar',
        data: [75, 68, 82, 60, 45],
        itemStyle: {
          color: '#5470c6'
        }
      }]
    };
    usageRateChartInstance.setOption(option);

    // 添加 resize 确保图表正确渲染
    usageRateChartInstance.resize();
  }
};

// 高峰时段图表 - 添加 resize
const initPeakTimeChart = () => {
  if (peakTimeChart.value) {
    peakTimeChartInstance = echarts.init(peakTimeChart.value);
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00']
      },
      yAxis: {
        type: 'value',
        name: '会议数量'
      },
      series: [{
        data: [12, 28, 35, 20, 18, 32, 40, 38, 25],
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#91cc75'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(145, 204, 117, 0.5)' },
            { offset: 1, color: 'rgba(145, 204, 117, 0.1)' }
          ])
        }
      }]
    };
    peakTimeChartInstance.setOption(option);

    // 添加 resize 确保图表正确渲染
    peakTimeChartInstance.resize();
  }
};

// 热门会议室图表 - 使用动态会议室名称并添加 resize
const initPopularRoomsChart = () => {
  if (popularRoomsChart.value) {
    popularRoomsChartInstance = echarts.init(popularRoomsChart.value);

    // 使用动态会议室名称
    const roomNames = availableRooms.value.slice(0, 5).map(room => room.name);

    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}次'
      },
      xAxis: {
        type: 'value',
        name: '预约次数'
      },
      yAxis: {
        type: 'category',
        data: roomNames
      },
      series: [{
        name: '预约次数',
        type: 'bar',
        data: [142, 128, 98, 85, 63],
        itemStyle: {
          color: '#fac858'
        }
      }]
    };
    popularRoomsChartInstance.setOption(option);

    // 添加 resize 确保图表正确渲染
    popularRoomsChartInstance.resize();
  }
};

// 会议用途图表 - 添加 resize
const initPurposeChart = () => {
  if (purposeChart.value) {
    purposeChartInstance = echarts.init(purposeChart.value);
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center'
      },
      series: [{
        name: '会议用途',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 35, name: '团队会议' },
          { value: 25, name: '客户洽谈' },
          { value: 20, name: '培训' },
          { value: 15, name: '面试' },
          { value: 5, name: '其他' }
        ]
      }]
    };
    purposeChartInstance.setOption(option);

    // 添加 resize 确保图表正确渲染
    purposeChartInstance.resize();
  }
};

// 会议时长图表 - 添加 resize
const initDurationChart = () => {
  if (durationChart.value) {
    durationChartInstance = echarts.init(durationChart.value);
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: '时长: {c} 分钟'
      },
      xAxis: {
        type: 'category',
        data: ['<30', '30-60', '60-90', '90-120', '>120']
      },
      yAxis: {
        type: 'value',
        name: '会议数量'
      },
      series: [{
        data: [25, 68, 102, 75, 30],
        type: 'bar',
        itemStyle: {
          color: '#ee6666'
        }
      }]
    };
    durationChartInstance.setOption(option);

    // 添加 resize 确保图表正确渲染
    durationChartInstance.resize();
  }
};

// 违规类型图表 - 添加 resize
const initViolationTypeChart = () => {
  if (violationTypeChart.value) {
    violationTypeChartInstance = echarts.init(violationTypeChart.value);
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}次'
      },
      legend: {
        bottom: 10,
        left: 'center'
      },
      series: [{
        name: '违规类型',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 42, name: '未按时结束' },
          { value: 28, name: '未签到使用' },
          { value: 15, name: '占用未预约' },
          { value: 10, name: '设备损坏' },
          { value: 5, name: '其他' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    };
    violationTypeChartInstance.setOption(option);

    // 添加 resize 确保图表正确渲染
    violationTypeChartInstance.resize();
  }
};

// 黑名单图表 - 添加 resize
const initBlacklistChart = () => {
  if (blacklistChart.value) {
    blacklistChartInstance = echarts.init(blacklistChart.value);
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}: {c}次违规'
      },
      xAxis: {
        type: 'category',
        data: ['张某某', '李某某', '王某某', '赵某某', '刘某某']
      },
      yAxis: {
        type: 'value',
        name: '违规次数'
      },
      series: [{
        data: [8, 6, 5, 4, 3],
        type: 'bar',
        itemStyle: {
          color: '#73c0de'
        }
      }]
    };
    blacklistChartInstance.setOption(option);

    // 添加 resize 确保图表正确渲染
    blacklistChartInstance.resize();
  }
};

// 设备使用频率图表 - 添加 resize
const initDeviceUsageChart = () => {
  if (deviceUsageChart.value) {
    deviceUsageChartInstance = echarts.init(deviceUsageChart.value);
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}次'
      },
      radar: {
        indicator: [
          { name: '投影仪', max: 100 },
          { name: '电视', max: 100 },
          { name: '电话', max: 100 },
          { name: '白板', max: 100 },
          { name: '视频会议', max: 100 },
          { name: '音响', max: 100 }
        ]
      },
      series: [{
        name: '设备使用频率',
        type: 'radar',
        data: [{
          value: [85, 70, 60, 75, 90, 65],
          name: '使用次数',
          areaStyle: {
            color: 'rgba(255, 182, 193, 0.5)'
          }
        }]
      }]
    };
    deviceUsageChartInstance.setOption(option);

    // 添加 resize 确保图表正确渲染
    deviceUsageChartInstance.resize();
  }
};

// 设备报修图表 - 添加 resize
const initRepairChart = () => {
  if (repairChart.value) {
    repairChartInstance = echarts.init(repairChart.value);

    // 设备列表
    const devices = ['投影仪', '空调', '电话', '视频会议', '座椅'];

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: devices
      },
      series: [{
        name: '报修次数',
        type: 'bar',
        data: [15, 12, 8, 5, 3],
        itemStyle: {
          color: '#5470c6'
        }
      }]
    };
    repairChartInstance.setOption(option);

    // 添加 resize 确保图表正确渲染
    repairChartInstance.resize();
  }
};

// 生成报表 - 添加 nextTick 确保 DOM 更新
const generateReport = () => {
  ElMessage.success('报表生成成功');
  nextTick(() => {
    renderCustomChart();
  });
};

// 导出报表保持不变...

// 渲染自定义图表 - 添加 resize
const renderCustomChart = () => {
  if (!customChart.value) return;

  if (!customChartInstance) {
    customChartInstance = echarts.init(customChart.value);
  }

  // 根据选择的报表类型显示不同图表
  const reportType = filterForm.value.reportType || 'usage';

  let option = {};
  switch(reportType) {
    case 'usage':
      option = getUsageChartOption();
      break;
    case 'booking':
      option = getBookingChartOption();
      break;
    case 'violation':
      option = getViolationChartOption();
      break;
    case 'resource':
      option = getResourceChartOption();
      break;
    default:
      option = getUsageChartOption();
  }

  customChartInstance.setOption(option);

  // 添加 resize 确保图表正确渲染
  customChartInstance.resize();
};

// 获取预约分析图表配置 - 使用动态会议室名称
const getBookingChartOption = () => {
  // 使用动态会议室名称
  const roomNames = availableRooms.value.slice(0, 5).map(room => room.name);

  return {
    title: {
      text: '会议室预约分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: roomNames // 动态会议室名称
    },
    yAxis: {
      type: 'value',
      name: '次数/分钟'
    },
    series: [
      {
        name: '预约次数',
        type: 'bar',
        data: [128, 85, 142, 98, 63]
      },
      {
        name: '平均时长',
        type: 'line',
        yAxisIndex: 0,
        data: [75, 60, 90, 80, 50],
        lineStyle: {
          width: 3
        }
      }
    ]
  };
};

// 获取违规分析图表配置
const getViolationChartOption = () => {
  return {
    title: {
      text: '会议室违规分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['违规次数', '涉及人数'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['未按时结束', '未签到使用', '占用未预约', '设备损坏', '其他']
    },
    yAxis: [
      {
        type: 'value',
        name: '违规次数'
      },
      {
        type: 'value',
        name: '涉及人数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '违规次数',
        type: 'bar',
        data: [42, 28, 15, 10, 5],
        itemStyle: {
          color: '#ee6666'
        }
      },
      {
        name: '涉及人数',
        type: 'line',
        yAxisIndex: 1,
        data: [25, 18, 12, 8, 4],
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#91cc75'
        }
      }
    ]
  };
};

// 获取资源分析图表配置
const getResourceChartOption = () => {
  return {
    title: {
      text: '资源使用分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['使用次数', '报修次数'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['投影仪', '电视', '电话', '白板', '视频会议', '音响']
    },
    yAxis: [
      {
        type: 'value',
        name: '使用次数'
      },
      {
        type: 'value',
        name: '报修次数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '使用次数',
        type: 'bar',
        data: [85, 70, 60, 75, 90, 65],
        itemStyle: {
          color: '#5470c6'
        }
      },
      {
        name: '报修次数',
        type: 'line',
        yAxisIndex: 1,
        data: [15, 8, 5, 3, 10, 6],
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#fac858'
        }
      }
    ]
  };
};


// 其他图表配置函数类似

onMounted(() => {
  // 使用 nextTick 确保所有 DOM 元素都已渲染
  nextTick(() => {
    initCharts();
  });

  window.addEventListener('resize', () => {
    const charts = [
      usageRateChartInstance, peakTimeChartInstance, popularRoomsChartInstance,
      purposeChartInstance, durationChartInstance, violationTypeChartInstance,
      blacklistChartInstance, deviceUsageChartInstance, repairChartInstance,
      customChartInstance
    ];

    charts.forEach(chart => {
      if (chart) chart.resize();
    });
  });
});
</script>

<style scoped>
.chart {
  width: 100%;
  height: 300px;
  min-height: 300px;
}

.chart-wrapper {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 15px;
  flex: 1;
  min-width: 300px;
  min-height: 350px;
  display: flex;
  flex-direction: column;
}

.chart-title {
  font-size: 1.1rem;
  font-weight: bold;
  text-align: center;
  margin-bottom: 15px;
  color: #333;
  flex-shrink: 0;
}

.statistics-report-container {
  padding: 20px;
}

.section-card {
  margin-bottom: 20px;
}

.custom-report-filters {
  margin-bottom: 20px;
}

.chart-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.chart-wrapper {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 15px;
  flex: 1;
  min-width: 300px;
}

.chart-title {
  font-size: 1.1rem;
  font-weight: bold;
  text-align: center;
  margin-bottom: 15px;
  color: #333;
}

.chart {
  width: 100%;
  height: 300px;
}

@media (max-width: 1200px) {
  .chart-wrapper {
    min-width: 45%;
  }
}

@media (max-width: 768px) {
  .chart-wrapper {
    min-width: 100%;
  }
}
</style>